package alert

import (
	"context"
	"fmt"
	"sync"

	"monitor.ilin.cc/config"
	"monitor.ilin.cc/internal/pkg/notify/wecom"
)

// WeComAlertService 企业微信告警服务
type WeComAlertService struct {
	robots []*wecom.Robot
	mu     sync.RWMutex
}

// NewWeComAlertService 创建企业微信告警服务
func NewWeComAlertService(cfg *config.AlertConfig) *WeComAlertService {
	var robots []*wecom.Robot

	// 遍历所有通道，找到类型为 wecom 的配置
	for _, channel := range cfg.Channels {
		if channel.Type == "wecom" {
			for _, robotCfg := range channel.Robots {
				robots = append(robots, wecom.NewRobot(&robotCfg))
			}
		}
	}

	return &WeComAlertService{robots: robots}
}

// SendAlert 发送告警消息
// level: 告警级别
// title: 告警标题
// content: 告警内容
func (s *WeComAlertService) SendAlert(level string, title string, content string) error {
	// 构建文本消息
	msg := wecom.NewTextMessage(fmt.Sprintf("%s\n级别: %s\n\n%s", title, level, content))

	// 发送到所有配置的机器人
	for _, robot := range s.robots {
		if err := robot.SendMessage(msg); err != nil {
			return fmt.Errorf("send to robot %s failed: %v", robot.Name(), err)
		}
	}
	return nil
}

// HandleAlert 处理告警
func (s *WeComAlertService) HandleAlert(ctx context.Context, alert *Alert) error {
	return s.SendAlert(alert.Level, alert.Title, alert.Content)
}

// GetAlertHistory 获取告警历史
func (s *WeComAlertService) GetAlertHistory(ctx context.Context, filter AlertFilter) ([]*AlertHistory, error) {
	// 暂不支持历史查询
	return nil, nil
}

// UpdateAlertRule 更新告警规则
func (s *WeComAlertService) UpdateAlertRule(ctx context.Context, rule *AlertRule) error {
	// 暂不支持规则更新
	return nil
}
